//
//  UIImage+TSFImage.m
//  Tool
//
//  Created by 积分宝 on 16/8/28.
//  Copyright © 2016年 谭少飞. All rights reserved.
//

#import "UIImage+TSFImage.h"

@implementation UIImage (TSFImage)
// 使用UIColor创建UIImage
+ (UIImage *)createImageWithColor: (UIColor *)color;{
    CGRect rect=CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
}
+(UIImage*)returnTwoDimensionCode:(NSString *)text{
    /**
     *  1.实例化二维码滤镜
     */
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    
    /**
     *  2.恢复滤镜的默认属性 (因为滤镜有可能保存上一次的属性)
     */
    [filter setDefaults];
    
    /**
     *  3.将字符串转换成NSdata
     */
    NSData *data  = [text dataUsingEncoding:NSUTF8StringEncoding];
    
    /**
     *  4.通过KVC设置滤镜, 传入data, 将来滤镜就知道要通过传入的数据生成二维码
     */
    [filter setValue:data forKey:@"inputMessage"];
    
    /**
     *  5.生成二维码
     */
    CIImage *outputImage = [filter outputImage];
    
    UIImage *image = [UIImage  imageWithCIImage:outputImage];
    
    /**
     *  6.设置生成好得二维码到imageview上
     */
    image = [image createNonInterpolatedUIImageFormCIImage:outputImage withSize:200];
    return image;
    
}
//改变二维码大小
- (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat) size {
    CGRect extent = CGRectIntegral(image.extent);
    CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
    // 创建bitmap;
    size_t width = CGRectGetWidth(extent) * scale;
    size_t height = CGRectGetHeight(extent) * scale;
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    CGContextScaleCTM(bitmapRef, scale, scale);
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    // 保存bitmap到图片
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    CGContextRelease(bitmapRef);
    CGImageRelease(bitmapImage);
    return [UIImage imageWithCGImage:scaledImage];
}

@end
